package com.guge.sports.toolPackage.utils;

import com.alibaba.excel.util.IoUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传工具类
 */
public class FileUploadUtils {


    //文件真实保存路径
    public final static String UPLOAD_PATH = "static/backend/upload/";


    //文件返回相对路径
    public final static String RELATIVE_PATH = "/backend/upload/";


    /**
     * 文件上传
     *
     * @param uploadFile 上传文件
     * @param path       子路径 例如： image  不需要/
     * @return
     * @throws IOException
     */
    public static String upload(MultipartFile uploadFile, String path) {
        //System.out.println("---------文件上传----------");
        //获取文件名
        String filename = uploadFile.getOriginalFilename();
        //System.out.println("filename="+filename);

        //System.out.println("realName===="+realName);

        String subString = filename.substring(filename.lastIndexOf("."));
        filename = UUID.randomUUID().toString().replaceAll("-", "") + subString;

        try {
            String realName = null;
            if (path == null) {
                realName = ResourceUtils.getURL("classpath:").getPath() + UPLOAD_PATH + "/";
            } else {
                realName = ResourceUtils.getURL("classpath:").getPath() + UPLOAD_PATH + path + "/";
            }

            File uploadfile = new File(realName);
            if (!uploadfile.exists()) {
                uploadfile.mkdirs();
            }
            uploadFile.transferTo(new File(realName + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return RELATIVE_PATH + path + filename;
    }


    /**
     * 文件下载
     *
     * @param response 响应
     * @param path     文件相对路径  例如：/backend/images/logo.png
     * @throws IOException
     */

    public static boolean download(HttpServletResponse response, String path) {

        try {
            //获取文件绝对路径
            String realName = ResourceUtils.getURL("classpath:").getPath() + "static" + path;
            File file = new File(realName);
            //获得输入流
            FileInputStream inputStream = new FileInputStream(file);

            // 设置响应头、以附件形式打开文件
            response.setHeader("content-disposition", "attachment; fileName=" + file.getName());
            String mimeType = ApplicationContextUtils.getServletContext().getMimeType(file.getAbsolutePath());
            //System.out.println("mimeType:" + mimeType);
            response.setCharacterEncoding("utf-8");
            response.setContentType(mimeType);
            response.addHeader("Content-Length", "" + file.length());
            //获得输出流对象
            ServletOutputStream outputStream = response.getOutputStream();
            IoUtils.copy(inputStream, outputStream);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }


  /*      int len = 0;
        byte[] data = new byte[1024];
        while ((len = inputStream.read(data)) != -1) {
            outputStream.write(data, 0, len);
        }
        outputStream.close();
        inputStream.close();
        return "redirect:/file";*/

    }




     /* // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        // EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data());
*/



    /*

     *//**
     * 文件上传
     *
     * @param request
     * @param path    文件保存路径
     *//*
    public static HashMap<String,String> fileUpload(HttpServletRequest request, String path) {
        String uploadPath = request.getRealPath("upload/");
        System.out.println("文件上传。。。");
        String str = null;
        String url = "upload/";
        HashMap<String,String>  hashMap = new HashMap<>();
        if (ServletFileUpload.isMultipartContent(request)) {
            //创建FileItemFactory 实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类ServletFileUpload
            ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
            // upload.setHeaderEncoding("utf-8");

            try {
                //解析上传的数据，得到一个表单项FileItem
                List<FileItem> list = upload.parseRequest(request);
                //循环判断，每一个表单项，是上传的文件还是普通类型
                for (FileItem fileItem : list) {
                    if (!fileItem.isFormField()) {
                        System.out.println("表单项的name属性值" + fileItem.getFieldName());
                        System.out.println("上传文件名" + fileItem.getName());

                        String fileName = UUID.randomUUID().toString() + fileItem.getName();
                        // String s = new String(fileItem.getName().getBytes(), "UTF-8");
                        //上传路径
                        if (path != null && !"".equals(path)) {
                            str = uploadPath + path + "/" + fileName;
                            url = url + path + "/" + fileName;
                        } else {
                            str = uploadPath + fileName;
                            url = url + fileName;
                        }
                        if (!"".equals(fileItem.getName())) {
                            fileItem.write(new File(str));
                            hashMap.put("imgName",url);
                        }else {
                            hashMap.put("imgName",null);
                        }
                    }else{
                        //用来保存普通的字段
                        String fieldName = fileItem.getFieldName();
                        String string = fileItem.getString("utf-8");
                        hashMap.put(fieldName, string);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return hashMap;
    }

    public static HashMap<String,String> fileUpload(HttpServletRequest request) {
        return fileUpload(request, null);
    }*/


    /**
     * 文件下载
     *
     * @param response
     * @param path     文件路径
    public static void fileDownload(ServletContext servletContext, HttpServletResponse response, String path) {
    try {
    String uploadPath =servletContext.getRealPath("upload/");
    System.out.println(uploadPath);
    File file = new File(uploadPath + path);
    String fileName = file.getName();
    System.out.println(uploadPath + path);
    System.out.println(fileName);
    String mimeType = servletContext.getMimeType(uploadPath + path);
    System.out.println("mimeType:" + mimeType);
    response.setContentType(mimeType);
    // 设置response的Header
    response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName));
    response.addHeader("Content-Length", "" + file.length());
    //InputStream resourceAsStream =servletContext.getResourceAsStream("upload/" + path);
    InputStream resourceAsStream =new FileInputStream(uploadPath + path);
    System.out.println(resourceAsStream);
    OutputStream outputStream = response.getOutputStream();
    System.out.println(outputStream);
    IoUtils.copy(resourceAsStream, outputStream);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }*/


    /* public static Map<String, String> imgFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     *//**
     * @Description: 上传图片文件方法
     * @Param: [request, response]
     * @Return: MAP
     *//*
        // 准备上传
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("GBK");
        PrintWriter out = response.getWriter();
        // 请求信息中的内容是否是multipart类型
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        // 获取到服务器项目的根目录下的userFile目录
        String uploadFilePath = request.getRealPath("/userFile");
        //判断请求信息中的内容 是否是“multipart/form-data”类型
        if (isMultipart) {
            //new一个 map用来保存图片名和普通表单的值
            HashMap<String, String> map = new HashMap<>();
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("UTF-8");
            //设置上传文件大小：单位 byte
            upload.setSizeMax(1024 * 1024 * 4);
            try {
                // 解析form表单中所有文件
                List<FileItem> items = upload.parseRequest(request);
                for (FileItem item : items) {
                    // 普通表单字段true, 文件表单字段false
                    if (!item.isFormField()) {
                        //文件名
                        String fileName = item.getName();
                        if (fileName != null && !"".equals(fileName)) {
                            String s = fileName.substring(fileName.lastIndexOf('.') + 1);
                            if (!"jpg".equals(s) && !"gif".equals(s) && !"bmp".equals(s) && !"png".equals(s) && !"txt".equals(s)) {
                                // 跳转路径
                                out.print("<script>alert('文件格式不正确！只能上传图片');location.href='/stuhome/index/homeAdd.html'</script>");
                            } else {
                                // 处理文件同名的问题，在文件名前添加UUID
                                String uuid = UUID.randomUUID().toString();
                                File saveFile = new File(uploadFilePath + "/" + uuid + "_" + fileName);
                                //上传
                                item.write(saveFile);
                                // 文件名
                                String homeImg = uuid + "_" + fileName;
                                map.put("imgName", homeImg);
                            }
                        }
                    } else {
                        //用来保存普通的字段
                        String fieldName = item.getFieldName();
                        String string = item.getString("utf-8");
                        map.put(fieldName, string);
                    }
                }
                return map;
            } catch (Exception e) {
                e.printStackTrace();
                out.print("<script>alert('文件大小超出范围，只能上传最多4M的文件！');location.href='/stuhome/index/homeAdd.html'</script>");
            }
        }
        return null;
    }
*/


    /*private static String getBasePath() {
        String str = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
        System.out.println(str);
        int index = str.indexOf("kzedu/");
        String basePath = str.substring(1, index + 6);
        //System.out.println("basePath:" + basePath);
        return basePath;
    }*/
}
